package com.ruoyi.web.controller.project;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购订单Controller
 * 
 * @author ruoyi
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/project/purchase/order")
@RequiredArgsConstructor
@Api(tags = "采购订单")
public class ProjectPurchaseOrderController extends BaseController{

    private final IProjectPurchaseOrderService projectPurchaseOrderService;

    private final IProjectPurchaseMaterialService projectPurchaseMaterialService;

    private final IProjectPurchaseService projectPurchaseService;

    private final IMessageService messageService;

    private final IProjectUserService projectUserService;

    private final IProjectService projectService;

    @GetMapping("/list")
    @ApiOperation("查询采购订单列表")
    public TableDataInfo list(@RequestParam(value = "projectId",required = false)Integer projectId,
                              @RequestParam(value = "userId",required = false)Long userId,
                              @RequestParam(value = "projectUserId",required = false)Long projectUserId,
                              @RequestParam(value = "projectPurchaseId",required = false)Integer projectPurchaseId)
    {
        startPage();
        QueryWrapper<ProjectPurchaseOrder> wrapper = new QueryWrapper<>();
        if (userId != null){
            wrapper.eq("project_id",projectId);
        }
        if (userId != null){
            wrapper.eq("purchase_user_id",userId);
        }
        if (projectUserId != null){
            QueryWrapper<ProjectUser> projectUserQueryWrapper = new QueryWrapper<>();
            projectUserQueryWrapper.eq("user_id",projectUserId);
            List<ProjectUser> projectUserList = projectUserService.list(projectUserQueryWrapper);
            if (projectUserList != null && projectUserList.size() > 0){
                wrapper.in("project_id",projectUserList.stream().map(ProjectUser::getProjectId).collect(Collectors.toList()));
            }
        }
        if (projectPurchaseId != null){
            wrapper.eq("project_purchase_id",projectPurchaseId);
        }
        wrapper.orderByDesc("created_time");
        List<ProjectPurchaseOrder> list = projectPurchaseOrderService.list(wrapper);
        return getDataTable(list);
    }



    @GetMapping(value = "/{id}")
    @ApiOperation("获取采购订单详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        ProjectPurchaseOrder order = projectPurchaseOrderService.getById(id);
        QueryWrapper<ProjectPurchaseMaterial> purchaseMaterialQueryWrapper = new QueryWrapper<>();
        purchaseMaterialQueryWrapper.eq("project_purchase_order_id",id);
        order.setProjectPurchaseMaterialList(projectPurchaseMaterialService.list(purchaseMaterialQueryWrapper));
        Project project = projectService.getById(order.getProjectId());
        order.setProjectName(project.getName());
        return success(order);
    }


    @Log(title = "采购订单", businessType = BusinessType.INSERT)
    @ApiOperation("新增采购订单")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ProjectPurchaseOrder projectPurchaseOrder)
    {
        projectPurchaseOrder.setPurchaseUserId(getUserId());
        projectPurchaseOrder.setCreatedTime(new Date());
        boolean save = projectPurchaseOrderService.save(projectPurchaseOrder);
        List<String> materialNameList = new ArrayList<>();
        projectPurchaseOrder.getPurchaseMaterialOrderList().forEach(m->{
            ProjectPurchaseMaterial projectPurchaseMaterial = projectPurchaseMaterialService.getById(m.getPurchaseMaterialId());
            projectPurchaseMaterial.setUnitPrice(m.getUnitPrice());
            projectPurchaseMaterial.setPrice(m.getPrice());
            projectPurchaseMaterial.setProjectPurchaseOrderId(projectPurchaseOrder.getId());
            projectPurchaseMaterial.setStatus(1);
            projectPurchaseMaterialService.updateById(projectPurchaseMaterial);
            materialNameList.add(projectPurchaseMaterial.getName());
        });
        ProjectPurchase projectPurchase = projectPurchaseService.getById(projectPurchaseOrder.getProjectPurchaseId());
        projectPurchase.setStatus(1);
        projectPurchaseService.updateById(projectPurchase);
        messageService.sendProjectMsgByUserIds(projectPurchase.getUserId().toString(), getNickName()+"采购【"+projectPurchase.getTitle()+"】订单【"+StringUtils.join(materialNameList,",")+"】");
        return toAjax(save);
    }


//    @Log(title = "采购订单", businessType = BusinessType.UPDATE)
//    @ApiOperation("修改采购订单")
//    @PostMapping("/edit")
//    public AjaxResult edit(@RequestBody ProjectPurchaseOrder projectPurchaseOrder)
//    {
//        return toAjax(projectPurchaseOrderService.updateById(projectPurchaseOrder));
//    }


    @Log(title = "采购订单", businessType = BusinessType.DELETE)
    @ApiOperation("删除采购订单")
	@PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        for (Integer id : ids) {
            QueryWrapper<ProjectPurchaseMaterial> wrapper = new QueryWrapper<>();
            wrapper.eq("project_purchase_order_id",id);
            List<ProjectPurchaseMaterial> list = projectPurchaseMaterialService.list(wrapper);
            ProjectPurchaseOrder purchaseOrder = projectPurchaseOrderService.getById(id);
            ProjectPurchase projectPurchase = projectPurchaseService.getById(purchaseOrder.getProjectPurchaseId());
            UpdateWrapper<ProjectPurchaseMaterial> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("project_purchase_order_id",null);
            updateWrapper.set("status",0);
            updateWrapper.set("price",null);
            updateWrapper.set("unit_price",null);
            updateWrapper.in("project_purchase_order_id",id);
            projectPurchaseMaterialService.update(updateWrapper);
            List<String> materialNameList = list.stream().map(ProjectPurchaseMaterial::getName).collect(Collectors.toList());
            messageService.sendProjectMsgByRoleIds(purchaseOrder.getProjectId(),"107,108,109,110,111", getNickName()+"删除【"+projectPurchase.getTitle()+"】订单【"+StringUtils.join(materialNameList,",")+"】");
        }
        boolean remove = projectPurchaseOrderService.removeBatchByIds(Arrays.asList(ids));
        return toAjax(remove);
    }

    @ApiOperation("收货")
    @GetMapping("/delivery")
    public AjaxResult delivery(@RequestParam("id")Integer id,
                               @RequestParam(value = "deliveryImg",required = false)String deliveryImg,
                               @RequestParam(value = "inventoryImg",required = false)String inventoryImg,
                               @RequestParam(value = "deliveryInfo",required = false)String deliveryInfo,
                               @RequestParam(value = "deliveryMemo",required = false)String deliveryMemo
                               ){
        ProjectPurchaseOrder purchaseOrder = projectPurchaseOrderService.getById(id);
        ProjectPurchase projectPurchase = projectPurchaseService.getById(purchaseOrder.getProjectPurchaseId());
        purchaseOrder.setDeliveryImg(deliveryImg);
        purchaseOrder.setDeliveryTime(new Date());
        purchaseOrder.setInventoryImg(inventoryImg);
        purchaseOrder.setDeliveryInfo(deliveryInfo);
        purchaseOrder.setDeliveryUserId(getUserId());
        purchaseOrder.setDeliveryMemo(deliveryMemo);
        boolean update = projectPurchaseOrderService.updateById(purchaseOrder);
        QueryWrapper<ProjectPurchaseMaterial> wrapper = new QueryWrapper<>();
        wrapper.eq("project_purchase_order_id",id);
        List<ProjectPurchaseMaterial> list = projectPurchaseMaterialService.list(wrapper);
        list.forEach(m->{
            projectPurchaseMaterialService.setStatus(m.getId(),2);
        });
        List<String> materialNameList = list.stream().map(ProjectPurchaseMaterial::getName).collect(Collectors.toList());
        messageService.sendProjectMsgByRoleIds(purchaseOrder.getProjectId(),"107,108,109,110,111","【"+projectPurchase.getTitle()+"】"+"订单【"+StringUtils.join(materialNameList,",")+"】"+getNickName()+"已收货");
        return toAjax(update);
    }


    @GetMapping("/editDelivery")
    @ApiOperation("修改收货情况")
    public AjaxResult editDelivery(@RequestParam("id")Integer id,
                                   @RequestParam("deliveryMethod")String deliveryMethod,
                                   @RequestParam("deliveryInfo")String deliveryInfo){
        ProjectPurchaseOrder projectPurchaseOrder = projectPurchaseOrderService.getById(id);
        projectPurchaseOrder.setDeliveryMethod(deliveryMethod);
        projectPurchaseOrder.setDeliveryInfo(deliveryInfo);
        return toAjax(projectPurchaseOrderService.updateById(projectPurchaseOrder));
    }
}
